//
//  WBOAuthViewController.swift
//  新浪微博
//
//  Created by ZJ on 2017/10/18.
//  Copyright © 2017年 zj. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {

    private lazy var webview = UIWebView()
    
    override func loadView() {
        view = webview
        
        view.backgroundColor = UIColor.white
        // 取消滚动视图
        webview.scrollView.isScrollEnabled = false
        
        webview.delegate = self
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "自动填充", target: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        guard let url = URL.init(string: urlString) else {
                return
        }
    
        let request = URLRequest.init(url: url)
        webview.loadRequest(request)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc private func close() {
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    
    /// 自动填充 - WebView 的注入
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '1345434023@qq.com';" + "document.getElementById('passwd').value = 'FZJFZR168518888';"
        
        webview.stringByEvaluatingJavaScript(from: js)
    }
}

extension WBOAuthViewController: UIWebViewDelegate {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            return true
        }
        
        // print("加载请求 --- \(request.url?.absoluteString)")
        // query url 后面所有部分
        // print("加载请求 --- \(request.url?.query)")
        
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            
            return false
        }
        
        //
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码 - \(code)")
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
//                SVProgressHUD.showInfo(withStatus: "登录成功")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
                // 关闭窗口
                self.close()
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
